﻿# CoffeeScript
@Cofe ?= {}

utils = Cofe.utils
Event = Cofe.Event

# MODEL - Represents a Atom Feed Item.
class Feed extends Spine.Model
  # id - feed item unique id
  @configure 'Feed', 'id'

  constructor: ->
    @events = []
    super

  init : =>        
    @status = "notready" 

 # Construct an EntryList from a url, which returns a COFEWS EntryList obj in json.
  Feed.fromUrl = (url) ->   
    new Feed({ url : url, links : {} })  

  # Construct FeedEvent from Atom feed item.
  Feed.fromXml = (data) ->          
    feed = new Feed()     
    feed.refresh(data)
    feed

  fetch : =>  
    @status = "working"
    $.ajax({
        url : @url
        dataType : 'xml'
      })

    .done (xhr, s, e) =>
       @trigger('fetched', @)
       @status = "fetched"
       @refresh(xhr)       

    .error (xhr, s, e) => 
       #console.log xhr
       @status = "error"
       log.error("Feed: Cannot load " + @url + " error " + xhr)     
       @trigger("error", @, "Failed to load " + @url)  

  refresh : (data) ->
    channel = $(data).find('channel')    
    @id = $(channel).children('a10\\:id').text()    
    @title = $(channel).children('title').text()
    @description = $(channel).children('description').text()
    @author = $(channel).find('author')?.find('name').text()      
    @lastBuildDate = $(channel).children('lastBuildDate').text()      
    @generator = $(channel).children('generator').text()          
    @events = (Cofe.Event.fromXml(fi) for fi in $(channel).find('item'))

    @links = {}
    for l in $(channel).children('a10\\:link')
      link = utils.parseLink(l)
      #console.log link
      @links[link.rel] = link
    
    @status = "ready"
    @trigger('refreshed', @)

Cofe.Feed = Feed

